package com.geek.bams.server;

import com.geek.bams.entity.Account;

import java.net.Socket;


public class ClientInfo {
    private Socket socket;
    private String ipAddress;
    private String port;
    private Account account; // 登录的账户信息
    private boolean isLoggedIn; // 是否已登录
    private long connectTime; // 连接时间
    
    public ClientInfo(Socket socket) {
        this.socket = socket;
        String address = socket.getRemoteSocketAddress().toString();
        // 解析IP和端口，格式：/127.0.0.1:52345
        if (address.startsWith("/")) {
            address = address.substring(1);
        }
        String[] parts = address.split(":");
        this.ipAddress = parts[0];
        this.port = parts.length > 1 ? parts[1] : "未知";
        this.isLoggedIn = false;
        this.connectTime = System.currentTimeMillis();
    }
    
    public Socket getSocket() {
        return socket;
    }
    
    public String getIpAddress() {
        return ipAddress;
    }
    
    public String getPort() {
        return port;
    }
    
    public Account getAccount() {
        return account;
    }
    
    public void setAccount(Account account) {
        this.account = account;
        this.isLoggedIn = (account != null);
    }
    
    public boolean isLoggedIn() {
        return isLoggedIn;
    }
    
    public long getConnectTime() {
        return connectTime;
    }
    
    /**
     * 获取连接时长（秒）
     */
    public long getConnectDuration() {
        return (System.currentTimeMillis() - connectTime) / 1000;
    }
    
    /**
     * 获取显示信息
     */
    public String getDisplayInfo() {
        if (isLoggedIn && account != null) {
            return String.format("IP: %s | AccountID: %d | Name: %s | Time: %ds",
                ipAddress, account.getId(), account.getName(), getConnectDuration());
        } else {
            return String.format("IP: %s | Socket: %s | Status: 未登录 | Time: %ds",
                ipAddress, port, getConnectDuration());
        }
    }
    
    @Override
    public String toString() {
        return getDisplayInfo();
    }
}

